<template>
  <div>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['md:school:contact:query']">
      <el-form-item label="姓名" prop="name">
        <el-input v-model.trim="queryParams.name" :maxlength="15" size="small" placeholder="请输入联系人姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model.trim="queryParams.phone" size="small" :maxlength="15" placeholder="请输入联系人手机号码"></el-input>
      </el-form-item>
      <el-form-item label="属性" prop="isImportant">
        <el-select v-model="queryParams.isImportant" size="small" filterable clearable placeholder="请选择属性" style="width: 100%;">
          <el-option
            v-for="item in isImportantList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['md:school:contact:query']" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['md:school:contact:query']" @click="resetForm('queryFormRef')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:school:contact:add']" @click="openDialog(null)">增加</el-button>
<!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:school:contact:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="600"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="姓名"
        align="center"
      />
      <el-table-column
        property="job"
        label="职务"
        align="center"
      />
      <el-table-column
        property="phone"
        label="手机号码"
        align="center"
      />
      <el-table-column
        property="email"
        label="邮箱"
        align="center"
      />
      <el-table-column
        property="nation"
        label="民族"
        align="center"
      />
      <el-table-column
        property="nativePlace"
        label="籍贯"
        align="center"
      />
      <el-table-column
        property="idcard"
        label="身份证号码"
        align="center"
      />
      <el-table-column
        property="isImportant"
        label="属性"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ getListValue(scope.row.isImportant, isImportantList) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="basis"
        label="重点依据"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="!scope.row.basis"></div>
          <div v-else v-for="(item, i) in scope.row.basis.split(',')" :key="i">{{ item }}</div>
<!--          <span>{{ scope.row.basis }}</span>-->
        </template>
<!--        <template slot-scope="scope">-->
<!--          <el-tooltip :content="scope.row.basis" placement="top">-->
<!--            <div-->
<!--              v-if="scope.row.basis"-->
<!--              class=" single-line-ellipsis"-->
<!--            >{{ scope.row.basis.length > 6 ? scope.row.basis.slice(0, 6) + "..." : scope.row.basis  }}</div>-->
<!--          </el-tooltip>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('md:school:contact:edit') || $auth.hasPermi('md:school:contact:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:school:contact:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['md:school:contact:remove']" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :autoScroll="false"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="600px"
      close-on-click-modal
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-row :gutter="20" v-if="form.type === 1">
          <el-col :span="12">
            <el-form-item
              label="代理商"
              prop="clientAgentId"
              :rules="[
            { required: true, message: '请选择代理商', trigger: 'change' },
          ]"
            >
              <el-select v-model="form.clientAgentId" filterable clearable placeholder="请选择代理商" style="width: 100%;">
                <el-option
                  v-for="item in agentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="faculty">
              <el-input v-model.trim="form.faculty" :maxlength="15" placeholder="请输入部门名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model.trim="form.name" :maxlength="15" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="job">
              <el-input v-model.trim="form.job" :maxlength="15" placeholder="请输入联系人职务"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model.trim="form.phone" :maxlength="15" placeholder="请输入联系人手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性" prop="isImportant" v-if="this.form.type === 0">
              <el-select
                v-model="form.isImportant"
                filterable
                clearable
                placeholder="请选择属性"
                style="width: 100%;"
                @change="changePropertyHandler"
              >
                <el-option
                  v-for="item in isImportantList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model.trim="form.email" :maxlength="50" placeholder="请输入联系人邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重点依据" prop="basis" v-if="this.form.type === 0 && this.form.isImportant === 1">
              <el-select
                v-model="form.basis"
                filterable
                multiple
                allow-create
                clearable
                placeholder="请选择重点依据"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in dict.type.sys_key_contact_basis"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-input v-model.trim="form.nation" :maxlength="30" placeholder="请输入联系人民族"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model.trim="form.nativePlace" :maxlength="100" placeholder="请输入联系人籍贯"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model.trim="form.idcard" :maxlength="50" placeholder="请输入联系人身份证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他联系方式" prop="other">
              <el-input v-model.trim="form.other" :maxlength="30" placeholder="请输入其他联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addDataApi, deleteDataApi, getDataListApi, updateDataApi } from "@/api/crm/md/contacts";
import { getDataListApi as getAllCustomerApi } from "@/api/crm/md/customer";
import { getDataListApi as getAllSchoolListApi } from "@/api/crm/md/school";
import { getDataListApi as getAllAgentListApi } from "@/api/crm/md/agent";
import { getUserProfile } from "@/api/system/user";
import { mapGetters } from 'vuex'
import { validatePhoneNumber } from "@/utils/validate";

export default {
  name: 'Contacts',
  dicts: ['sys_key_contact_basis'],
  data() {

    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'));
      }

      if (!validatePhoneNumber(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 联系人类型
      contactTypeList: [
        {
          value: 0,
          label: '客户'
        },
        {
          value: 1,
          label: '代理商'
        }
      ],
      // 新增和修改参数
      form: {
        customerId: null, // 客户id
        basis: [], // 重点联系人依据
        clientAgentId: null, // 代理商/二级部门id *
        createBy: "", // 用户 *
        createTime: "", // 创建时间 *
        faculty: "", // 二级部门名称
        id: null,
        isImportant: 0, // 是否重点联系人 *
        job: "", // 职务
        name: "", // 联系人姓名 *
        nation: "", // 民族
        nativePlace: "", // 籍贯
        other: "", // 其他联系方式
        phone: "", // 手机号 *
        remark: "", // 备注
        schoolOrCompanyName: "", // 学校/公司名称
        type: 0, // 类别 0是客户 1是代理商 *
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
        idcard: "", // 身份证号
        email: "", // 邮箱
      },
      // 重点联系人下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通联系人'
        },
        {
          value: 1,
          label: '重点联系人'
        }
      ],
      // 表单的校验规则
      rules: {
        job: [
          {required: true, message: '请填写联系人职务', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请填写客户名称', trigger: 'blur'}
        ],
        idcard: [
          {
            pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        // other: [
        //   {
        //     type: "email",
        //     message: "请输入正确的邮箱地址",
        //     trigger: ["blur", "change"]
        //   }
        // ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        basis: [
          {required: true, message: '请选择重点依据', trigger: 'change'}
        ],
        isImportant: [
          {required: true, message: '请选择联系人属性', trigger: 'change'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        clientAgentId: null, // 院系或者代理商ID
        schoolOrCompanyName: "",
        faculty: "",
        phone: "", // 手机号 *
        name: "", // 联系人姓名 *
        isImportant: null, // 是否重点客户 0是普通 1是重点 *
        type: null, // 类别 0是客户 1是代理商 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 全部客户信息
      customerList: [],
      // 全部二级部门信息
      schoolList: [],
      // 全部代理商信息
      agentList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  props: ['schoolInfo', 'type'],
  watch: {
    schoolInfo: {
      deep: true,
      immediate: true,
      handler(newV) {
        // this.queryParams.faculty = newV.name
        this.queryParams.clientAgentId = newV.id
        this.getList()
      }
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = []
        }
      }
    },
  },
  created() {
    // this.getList()
    this.getUserinfo()
    // this.getAllCustomerList()
    this.getAllAgentList()
  },
  methods: {
    // 选择重点依据的回调
    // async selectBasisChange(val) {
    //   if(!val.length) return false
    //   const dictName = "sys_key_contact_basis"
    //   const oList = this.dict.type[dictName].map(i => i.value)
    //   const list = findItemsNotInOrigin(val, oList)

    //   /*
    //   * dictLabel: "1"
    //   * dictSort: 1111
    //   * dictType: "sys_key_plan"
    //   * dictValue: "1"
    //   * listClass: "default"
    //   * status: "0"
    //   * */
    //   if(!list.length) return false
    //   const payload = {
    //     dictLabel: list[0],
    //     dictSort: this.dict.type[dictName].length,
    //     dictType: dictName,
    //     dictValue: list[0],
    //     listClass: "default",
    //     status: "0"
    //   }

    //   // 增加字典数据
    //   await addData(payload)

    //   // 重新获取字典数据
    //   const res = await this.getDicts(dictName)
    //   if(res.code === 200) {
    //     this.dict.type[dictName] = (res.data ?? []).map((i) => {
    //       return new DictData(i.dictLabel, i.dictValue, i)
    //     })
    //   }

    //   await refreshCache()
    // },
    // 选择重点的回调
    changePropertyHandler(val) {
      if(val === '0') {
        this.form.basis = []
      }
    },
    // 选择二级部门的回调
    changeSchoolHandler(val) {
      if(typeof val === 'number') {
        const school = this.getListValue(val, this.schoolList)
        this.form.faculty = school
      }
    },
    // 选择客户的回调
    changeCustomerHandler(val) {
      if(typeof val === 'number') {
        this.getAllSchoolList(val)
      }
    },
    // 获取全部客户
    getAllCustomerList() {
      getAllCustomerApi().then((res) => {
        this.customerList = res.rows
      })
    },
    // 获取全部二级部门
    getAllSchoolList(clientId) {
      getAllSchoolListApi({ clientId }).then((res) => {
        this.schoolList = res.rows
      })
    },
    // 获取全部代理商
    getAllAgentList() {
      getAllAgentListApi().then((res) => {
        this.agentList = res.rows
      })
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi({
        ...this.queryParams,
        type: this.type
      })
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {
          ...row,
          basis: (row.basis?.split(',') ?? []).filter(i => i)
        }
        this.dialogTitle = 2
        this.changeCustomerHandler(row.customerId)
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.form.type = this.type
      this.form.clientAgentId = this.schoolInfo.id
      this.form.customerId = this.schoolInfo.clientId
      this.form.schoolOrCompanyName = this.schoolInfo.clientName
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/contact/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `contacts_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if (this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
        isImportant: this.form.type === 0 ? this.form.isImportant : 0,
        basis: this.form.type === 0 ? this.form.basis.join(',') : [],
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs.formRef.resetFields()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
        isImportant: this.form.type === 0 ? this.form.isImportant : 0,
        basis: this.form.type === 0 ? this.form.basis.join(',') : [],
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.form.type = this.type
      this.form.clientAgentId = this.schoolInfo.id
      this.form.customerId = this.schoolInfo.clientId
      this.form.schoolOrCompanyName = this.schoolInfo.clientName
    }
  },
}
</script>
<style scoped lang="scss">

</style>
